import { useEffect, useMemo, useState } from "react";
import { createPortal } from "react-dom";
import { getComponentById, useComponentsStore } from "@/stores/edit-pages-store";
import { useComponentConfigStore, getComponentConfByName, ComponentConfig } from "@/stores/low-editor-comps-conf";
import { Divider, Dropdown, Popconfirm, Space } from "antd";
import { ClearOutlined, DeleteOutlined } from "@ant-design/icons";
import { useSize } from "ahooks";
import { updatePosition, EditPositionType } from "../commonMethods";
import "./index.scss";
interface SelectedMaskProps {
  portalWrapperClassName: string;
  containerClassName: string;
  componentId: string;
}

function SelectedMask({ containerClassName, portalWrapperClassName, componentId }: SelectedMaskProps) {
  const [position, setPosition] = useState({
    left: 0,
    top: 0,
    width: 0,
    height: 0,
    labelTop: 0,
    labelLeft: 0,
  });
  const [editPosition, setEditPosition] = useState<EditPositionType>({
    left: 0,
    top: 0,
    width: 0,
    height: 0,
    borderWidth: "0px",
  });

  const { schema, curComponent, popEditing, deleteComponent, setCurComponentId, clearComponentSubitems, curComponentUnitType } =
    useComponentsStore();

  const { componentConfig } = useComponentConfigStore();
  const componentConf = getComponentConfByName(curComponent?.name, componentConfig) as ComponentConfig

  const el = useMemo(() => {
    return document.querySelector(`.${portalWrapperClassName}`)!;
  }, []);

  const [changePin, setChangePin] = useState(0)

  //监测选中状态resize后的变化
  const { width } = useSize(el) ?? {};

  useEffect(() => {
    updatePosition({
      componentId,
      curComponent,
      containerClassName,
      curComponentUnitType,
      schema,
      setPosition,
      setEditPosition,
      popEditing,
      componentConf
    });
  }, [componentId, curComponentUnitType, width]);

  useEffect(() => {
    setTimeout(() => {
      updatePosition({
        componentId,
        curComponent,
        containerClassName,
        curComponentUnitType,
        schema,
        setPosition,
        setEditPosition,
        popEditing,
        componentConf
      });
    }, 300);
  }, [schema]);

  function handleDelete() {
    deleteComponent(componentId);
    setCurComponentId(null);
    setChangePin(new Date().getTime())
  }
  function handleClearChildren() {
    clearComponentSubitems(componentId, curComponentUnitType);
    setChangePin(new Date().getTime())
  }

  const parentComponents = useMemo(() => {
    const parentComponents = [];
    let component = curComponent;
    while (component?.parentId) {
      component = getComponentById(component.parentId, schema);
      if (component) {
        parentComponents.push(component);
      }
    }
    return parentComponents;
  }, [curComponent]);

  const clearRegion = useMemo(()=>{
    const type = curComponentUnitType || (componentConf.defaultEditRegion ?? "body")
    return curComponent?.[type] || []
  },[curComponent,curComponentUnitType,changePin])
  if (!curComponent) return null;
  return createPortal(
    <>
      <div
        className="maskOuterContainer"
        style={{
          position: "absolute",
          left: position.left,
          top: position.top,
          pointerEvents: "none",
          width: position.width,
          height: position.height,
          zIndex: 12,
        }}
      >
        {!!editPosition && curComponentUnitType &&(
          <div
            className="maskInnerRegion"
            style={{
              borderColor: "rgba(0, 0, 255, 0.05)",
              borderWidth: editPosition.borderWidth,
              borderStyle: "solid",
              pointerEvents: "none",
              width: position.width,
              height: "100%",
            }}
          >
            { clearRegion.length>0 &&<Space
              split={
                <Divider
                  type="vertical"
                  style={{ borderInlineStart: "1px solid #fff", opacity: 0.4, marginInline: "4px" }}
                />
              }
              size={2}
              className="bg-blue-600 text-xs h-[18px] px-2 text-white rounded-b"
              style={{
                position: "absolute",
                left: "50%",
                top: 0,
                fontSize: "12px",
                pointerEvents: "auto",
                transform: "translateX(-50%)",
              }}
            >
              <Popconfirm title="确认清空？" okText={"确认"} cancelText={"取消"} onConfirm={handleClearChildren}>
                <ClearOutlined className="selectToolIcon" />
              </Popconfirm>
            </Space>}
          </div>
        )}
      </div>
      <div
        style={{
          position: "absolute",
          left: position.left,
          top: position.labelTop,
          fontSize: "14px",
          zIndex: 13,
          display: !position.width || position.width < 10 ? "none" : "inline",
          transform: "translateY(-100%)",
        }}
      >
        <Space
          split={
            <Divider
              type="vertical"
              style={{ borderInlineStart: "1px solid #fff", opacity: 0.4, marginInline: "4px" }}
            />
          }
          size={2}
          className="bg-blue-600 text-xs h-6 px-2 text-white"
        >
          <Dropdown
            menu={{
              items: parentComponents.map(item => ({
                key: item.id,
                label: item.name,
              })),
              onClick: ({ key }) => {
                setCurComponentId(key);
              },
            }}
            disabled={parentComponents.length === 0 || ["Modal"].includes(curComponent.name)}
          >
            <div className="cursor-pointer whitespace-nowrap"> {curComponent.desc} </div>
          </Dropdown>

          {!["Page", "PageAside", "PageMain", "Modal"].includes(curComponent.name) && (
            <Popconfirm title="确认删除？" okText={"确认"} cancelText={"取消"} onConfirm={handleDelete}>
              <DeleteOutlined className="selectToolIcon" />
            </Popconfirm>
          )}
        </Space>
      </div>
    </>,
    el
  );
}

export default SelectedMask;
